package com.hxd.buybooksystem.ui.fragment

import android.annotation.SuppressLint
import android.app.Dialog
import android.support.v7.widget.LinearLayoutManager
import android.view.View
import android.widget.TextView
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.FindListener


import cn.bmob.v3.BmobQuery
import com.hjq.base.BaseDialog
import com.hjq.dialog.PayPasswordDialog
import com.hjq.dialog.ToastDialog
import com.hjq.dialog.WaitDialog
import com.hxd.buybooksystem.R
import com.hxd.buybooksystem.adapter.BuyCarOrderAdapter
import com.hxd.buybooksystem.base.common.MyLazyFragment
import com.hxd.buybooksystem.bean.BookInfo
import com.hxd.buybooksystem.bean.Order
import com.hxd.buybooksystem.ui.activity.MainActivity
import com.hxd.buybooksystem.uitls.L
import com.hxd.tabactivityfragment.util.ThreadUtil
import kotlinx.android.synthetic.main.fragment_buy_car.*
import java.util.logging.Handler

/**
 *  项目名：    BuyBookSystem
 *  包名：      com.hxd.buybooksystem.ui.fragment
 *  文件名:     IndexFragment
 *  创建者:     HXD
 *  创建时间:   2019/5/28 20:19
 *  描述:       购物车页面
 */

class BuyCarFragment : MyLazyFragment<MainActivity>() {

    private val orders by lazy { ArrayList<Order>() }
    private val bookInfos by lazy { ArrayList<BookInfo>() }
    private var orderAdapter:BuyCarOrderAdapter? = null

    val waitDialog: BaseDialog by lazy {
        WaitDialog.Builder(activity)
            .setMessage("购买中...")
            .show()
    }

    val successDialog: BaseDialog by lazy {
        ToastDialog.Builder(activity)
            .setType(ToastDialog.Type.FINISH)
            .setMessage("购买成功")
            .show()
    }

    //设置单例静态方法
    companion object {
        fun newInstance(): BuyCarFragment {
            return BuyCarFragment()
        }
    }

    override fun getLayoutId(): Int {
        return R.layout.fragment_buy_car
    }

    override fun getTitleBarId(): Int {
        return R.id.tb_title_buy_car
    }

    @SuppressLint("ResourceAsColor")
    override fun initView() {
        loadData()

        btn_goPay_buyCar.setOnClickListener {
            var sum = 0f
            orderAdapter!!.getSumPrice().forEach {
                sum += it
            }

            PayPasswordDialog.Builder(activity)
                .setTitle("请输入支付密码")
                .setSubTitle("用于购买所有图书")
                .setMoney("￥ $sum")
                //.setAutoDismiss(false) // 设置点击按钮后不关闭对话框
                .setListener(object : PayPasswordDialog.OnListener {
                    override fun onCompleted(dialog: Dialog, password: String) {
                        waitDialog
                        orderAdapter!!.setPay()
                        orders.clear()

                        ThreadUtil.postRunOnMainThread(Runnable {
                            waitDialog.dismiss()
                            loadData()
                            successDialog
                        })
                    }

                    override fun onCancel(dialog: Dialog) {
                        toast("取消了")
                    }
                })
                .show()
        }
    }

    override fun initData() {

    }

    /**
     * 加载网络数据
     */
    private fun loadData(){
        val query = BmobQuery<Order>()
        query.findObjects(object : FindListener<Order>() {
            override fun done(litis: MutableList<Order>, e: BmobException?) {
                if (e == null) {
                    litis.forEach {
                        if (!it.isPay){
                            orders.add(it)
                        }
                    }
                    val bannerQuery = BmobQuery<BookInfo>()
                    bannerQuery.findObjects(object : FindListener<BookInfo>() {
                        override fun done(lists: MutableList<BookInfo>, e: BmobException?) {
                            ThreadUtil.runOnMainThread(Runnable {
                                if (e == null) {
                                    lists.forEach {
                                        bookInfos.add(it)
                                    }
                                    initRecycle()
                                } else {
                                    L.i("IndexBookInfo查询失败：" + e.errorCode)
                                }
                            })
                        }
                    })

                } else {
                   L.i("订单数据查询失败")
                }
            }
        })
    }

    /**
     * 初始化Recycle
     */
    private fun initRecycle(){
        //设置适配器
        orderAdapter = BuyCarOrderAdapter(orders, bookInfos)
        recycle_buy_car.adapter = orderAdapter
        val linearManage = LinearLayoutManager(context)
        linearManage.orientation = LinearLayoutManager.VERTICAL
        recycle_buy_car.layoutManager = linearManage

        if(orders.isEmpty()){
            btn_goPay_buyCar.visibility = View.GONE
        }else{
            btn_goPay_buyCar.visibility = View.VISIBLE
        }

    }

    override fun isStatusBarEnabled(): Boolean {
        // 使用沉浸式状态栏
        return !super.isStatusBarEnabled()
    }
}